package mobile

import (
	"fmt"
	"math/rand"
	"os"
	"path"
	"strings"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// "sword"

type Column struct {
	BaseController
}

func (c *Column) Get() {
	column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0 and gid=0 order by sort desc,addtime asc`)
	column_level2 := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + column[0]["id"].(string) + ` and gid=0 
		order by sort desc,addtime asc`)
	for _, v := range column_level2 {
		v["column_level3"] = models.Query(`select a.id,a.name,b.pathname from mt_column a left join mt_resources b on a.img=b.id 
			where a.type='p' and a.status=1 and a.pid=` + v["id"].(string) + ` and a.gid=0 order by a.sort desc,a.addtime asc`)
	}
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["column"] = column
		js["column_level2"] = column_level2
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		/*标题*/
		c.Data["title"] = "分类"
		c.Data["s_title"] = `产品分类`
		c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
		c.Data["column"] = column
		c.Data["column_level2"] = column_level2
		c.TplName = "wechat/column/index.html"
	}
}
func (c *Column) Post() {
	defer c.ServeJSON()
	column_level2 := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + c.GetString("id") + ` and gid=0 
		order by sort desc,addtime asc`)
	for _, v := range column_level2 {
		v["column_level3"] = models.Query(`select a.id,a.name,b.pathname from mt_column a left join mt_resources b on a.img=b.id 
			where a.type='p' and a.status=1 and a.pid=` + v["id"].(string) + ` and a.gid=0 order by a.sort desc,a.addtime asc`)
	}
	c.Data["json"] = column_level2
}

type ColumnSearch struct {
	BaseController
}

func (c *ColumnSearch) Get() {
	keywords := models.Query(`select title from mt_keywords where status=1 and type=1 and hot=1 order by sort desc`)
	if c.IsAjax() {
		c.Data["json"] = keywords
		c.ServeJSON()
	} else {

		c.Data["keywords"] = keywords
		c.Data["title"] = `搜索`
		c.Data["s_title"] = `产品搜索`
		c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
		c.TplName = "wechat/column/search.html"
	}
}

type ColumnSearchResult struct {
	BaseController
}

func (c *ColumnSearchResult) Get() {
	shopWhere := ""
	if c.ShopId != "" {
		shopWhere = " a.gid = " + c.ShopId
	} else {
		shopWhere = " a.gid not in(select id from mt_shop where style=1)"
	}
	keywords := c.GetString("keywords")
	keywords2 := c.GetString("keywords2")
	if keywords2 != "" {
		keywords = keywords2
	}
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	var w2 []string
	var isb = false
	if keywords != "" {

		w2 = append(w2, `a.title like '%`+keywords+`%'`)
		w2 = append(w2, `a.keywords like '%`+keywords+`%'`)
		w2 = append(w2, `a.model like '%`+keywords+`%'`)
		//w2 = append(w2, `a.barcode like '%`+keywords+`%'`)
		c.Data["s_title"] = `搜索结果`
		c.Data["s_desc"] = `关键词:` + keywords
		brand := models.Query(`select * from mt_brand where name like '%` + keywords + `%'`)
		if brand != nil {
			isb = true
		}
	}
	w2s := strings.Join(w2, ` or `)
	if w2s != "" {
		w2s = `(` + w2s + `)`
		w = append(w, w2s)
	}

	status := c.GetString("status")
	var ob string
	switch status {
	case "":
		if isb {
			ob = ` order by l.pid`
		} else {

			ob = ` order by a.addtime desc`
		}
	case "0":
		ob = ` order by a.price desc`
	case "1": //价格
		ob = ` order by a.price`
	case "2": //销量
		ob = ` order by a.sellnum desc`
	case "3": //销量
		ob = ` order by a.addtime desc`
	}
	bid := c.GetString("bid")
	if bid != "" {
		c.Data["s_title"] = models.Query(`select name from mt_brand where id=` + bid)[0]["name"]
		w = append(w, `a.bid=`+bid)
		switch status {
		case "":
			ob = ` order by l.pid`
		case "0":
			ob = ` order by a.price desc`
		case "1": //价格
			ob = ` order by a.price`
		case "2": //销量
			ob = ` order by a.sellnum desc`
		case "3": //销量
			ob = ` order by a.addtime desc`
		}
	}
	/*statusajax := c.GetString("statusajax")
	if statusajax == "" {
		switch status {
		case "":
			if isb {
				ob = ` order by l.pid`
			} else {

				ob = ` order by a.addtime desc`
			}
		case "0":
			ob = ` order by a.price desc`
		case "1": //价格
			ob = ` order by a.price`
		case "2": //销量
			ob = ` order by a.sellnum desc`
		case "3": //销量
			ob = ` order by a.addtime desc`
			c.Data["s_title"] = "新品"
		}
	} else {
		switch statusajax {
		case "":
			if isb {
				ob = ` order by l.pid`
			} else {

				ob = ` order by a.addtime desc`
			}
		case "0":
			ob = ` order by a.price desc`
		case "1": //价格
			ob = ` order by a.price`
		case "2": //销量
			ob = ` order by a.sellnum desc`
		case "3": //销量
			ob = ` order by a.addtime desc`
		}
	}
	bid := c.GetString("bid")
	if bid != "" {
		c.Data["s_title"] = models.Query(`select name from mt_brand where id=` + bid)[0]["name"]
		w = append(w, `a.bid=`+bid)
		if statusajax == "" {
			switch status {
			case "":
				// ob = ` order by l.pid desc,a.cid desc,a.recommend desc,a.sort desc`
				ob = ` order by l.pid`
			case "0":
				ob = ` order by a.cid desc,a.price desc`
			case "1": //价格
				ob = ` order by a.price`
			case "2": //销量
				ob = ` order by a.sellnum desc`
			case "3": //销量
				ob = ` order by a.addtime desc`
			}
		} else {
			switch statusajax {
			case "":
				ob = ` order by l.pid`
			case "0":
				ob = ` order by a.cid desc,a.price desc`
			case "1": //价格
				ob = ` order by a.price`
			case "2": //销量
				ob = ` order by a.sellnum desc`
			case "3": //销量
				ob = ` order by a.addtime desc`
			}
		}
	}*/
	w = append(w, shopWhere)
	ws := strings.Join(w, ` and `)
	page, _, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `
		select a.title,a.keywords,a.price,a.id,a.isvip,a.minbuy,a.sellnum,a.issellnum,b.pathname,c.name as gname,c.id as gid,a.addtime,d.name as shen 
		from mt_product a 
		left join mt_resources b on a.img=b.id 
		left join (select * from mt_shop where status=1 and censoring=1) c on a.bid=c.bid 
		left join mt_area d on c.province=d.code 
		left join mt_column l on a.cid=l.id
		where ` + ws + ` group by a.barcode` + ob + lt
	//beego.Debug(sql)
	info := ProductList(sql, c.Uid)
	if c.IsAjax() {
		c.Data["json"] = info
		c.ServeJSON()
	} else {
		c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
		c.Data["status"] = status
		c.Data["info"] = info
		c.Data["keywords"] = keywords
		c.Data["title"] = `搜索结果`
		c.Data["urls"] = `/mobile/column/search_result?keywords=` + keywords
		c.Data["urlajax"] = `/mobile/column/search_result?keywords=` + keywords + `&status=` + status
		c.TplName = "wechat/column/search_result.html"
	}
}

type ColumnProductContent struct {
	BaseController
}

func (c *ColumnProductContent) Get() {
	shopWhere := ""
	if c.ShopId != "" {
		shopWhere = "a.gid = " + c.ShopId + " and"
	}
	Isajax := c.IsAjax()
	id := c.GetString("id")
	now := sword.Gettimes("")
	shopcarnum := ""
	if id != "" {
		if product := models.Query(`select a.issingle,a.id,a.barcode,a.title,a.price,a.image,a.cid,a.content,a.click,a.length,a.description,a.minbuy,a.size,d.style,
			a.attr,a.width,a.height,a.weight,a.number,a.spec,a.material,a.isvip,a.inventory,a.sellnum,a.issellnum,a.model,b.pathname,c.name as bname,d.id as gid,d.name as cname,e.pathname as cimg
			 from mt_product a left join mt_resources b on a.img=b.id left join mt_brand c on a.bid=c.id left join mt_shop d on a.bid=d.bid left join mt_resources e on e.id=d.logo
			  where ` + shopWhere + ` a.id=` + id + ` and a.censoring=1 and a.status=1`); product != nil {
			// 阅读记录
			gid := fmt.Sprint(product[0]["gid"])
			ProductClick(id, c.Uid)
			var iscollect int
			if c.Uid != "" {
				if isc := models.Query(`select id from mt_member_collection where uid=` + c.Uid + ` and pid=` + id); isc != nil {
					iscollect = 1
				}
				shopcarnum = models.Query(`select count(a.id) as num from mt_order_car a where a.type in (0,2) and a.status=1 and a.uid=` + c.Uid)[0]["num"].(string)
			}
			for _, v := range product {
				//轮播图
				var img []string
				if pathname, ok := v["pathname"].(string); ok {
					img = append(img, pathname)
				}
				if image := fmt.Sprint(v["image"]); image != "" && image != "<nil>" {
					imgs := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
					for _, i := range imgs {
						p := fmt.Sprint(i["pathname"])
						if c.ShopId != "" {
							pathname := strings.TrimLeft(p, "/")
							ext := path.Ext(pathname)
							source := strings.TrimRight(pathname, ext) + "-source" + ext
							isExists, _ := PathExists(source)
							if !isExists {
								source = pathname + "-source" + strings.ToLower(ext)
								isExists, _ = PathExists(source)
								if !isExists {
									source = pathname
								}
							}
							source = "/" + source
							img = append(img, source)
						} else {
							img = append(img, p)
						}
					}
				}
				v["imgs"] = img
				if c.ShopId != "" {
					content := fmt.Sprint(v["content"])
					if content != "" {
						imgs := sword.UeditorImg(content)
						for _, v := range imgs {
							pathname := strings.TrimLeft(v, "/")
							ext := path.Ext(pathname)
							source := strings.TrimRight(pathname, ext) + "-source" + ext
							isExists, _ := PathExists(source)
							if !isExists {
								source = pathname + "-source" + strings.ToLower(ext)
								isExists, _ := PathExists(source)
								if !isExists {
									source = pathname
								}
							}
							content = strings.Replace(content, pathname, source, -1)
						}
					}
					product[0]["content"] = content
				}
				//价格
				price := fmt.Sprint(v["price"])
				number := fmt.Sprint(v["number"])
				v["pricem"] = sword.Mult(price, number)
				if sales := models.Query(`select price from mt_active_sales where pid=` + id + ` and status=1 and end=0 and 
					starttime<='` + now + `' and endtime>='` + now + `'`); sales != nil {
					price := fmt.Sprint(sales[0]["price"])
					v["price"] = price
					pricem := sword.Mult(price, fmt.Sprint(number))
					v["pricem"] = pricem
				}
				if c.Uid != "" {
					if fmt.Sprint(v["isvip"]) == "1" {
						var gid string
						g := models.Query(`select b.id,b.style 
								from mt_product a 
								left join mt_shop b on a.gid=b.id 
								where a.id=?`, id)[0]
						if fmt.Sprint(g["style"]) == "0" || g["id"] == nil {
							gid = "0"
						} else {
							gid = fmt.Sprint(g["id"])
						}
						//beego.Debug(c.Uid)
						//beego.Debug(gid)
						mem := models.Query(`
									select b.fold 
									from mt_member_vip_order a 
									join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
									where a.uid=?`, gid, c.Uid)
						if mem != nil {
							if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
								//beego.Debug(v["price"])
								//beego.Debug(fold)
								vprice := sword.Divi(sword.Mult(fmt.Sprint(v["price"]), fold), "100")
								//beego.Debug(vprice)
								v["price"] = vprice
								v["pricem"] = sword.Mult(vprice, number)
							}
						} else {
							v["isvip"] = "0"
						}
					}
				}

				//销量
				if fmt.Sprint(v["issellnum"]) == "1" {
					sellnum := models.Query(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.pid=` + v["id"].(string))[0]["num"]
					if sellnums, ok := sellnum.(string); ok {
						v["sellnum"] = sellnums
					} else {
						v["sellnum"] = "0"
					}
				}
				attr := fmt.Sprint(v["attr"])
				attr = strings.Trim(attr, ",")
				if attr == "" || attr == "<nil>" {
					attr = "''"
				}
				var attrs []orm.Params
				var attro = make(orm.Params)
				attro["name"] = "条形码"
				attro["value"] = v["barcode"]
				attrs = append(attrs, attro)
				vattr := models.Query(`select a.name as value,b.name from mt_product_attribute a left join mt_product_attribute_column
				 b on a.cid=b.id where a.id in(` + attr + `) order by b.sort desc`)
				for _, a := range vattr {
					attrs = append(attrs, a)
				}
				v["attrs"] = attrs
				v["parameter"] = models.Query(`select a.key,a.value from mt_product_parameter a where a.pid=` + id + ` and a.status=1 order by a.sort desc`)
			}
			cid := fmt.Sprint(product[0]["cid"].(string))
			var shop orm.Params
			var gidcou = "0"
			if gid != "0" {
				if shops := models.Query(`select a.id,a.tel,a.name,b.pathname,c.name as shen,d.name as shi,e.name as qu from mt_shop a 
					left join mt_resources b on a.logo=b.id left join mt_area c on a.province=c.code left join mt_area d on a.city=d.code 
					left join mt_area e on a.area=e.code where a.id=` + gid); shops != nil {
					shop = shops[0]
					gidcou = gid
				}
			}
			recommend := ProductList(`select a.price,a.id,b.pathname,a.title,a.isvip from mt_product a left join mt_resources b on 
				a.img=b.id where a.cid=`+cid+` and a.status=1 and a.censoring=1 and a.recommend=1 and a.id<>`+id+` and gid=`+gidcou+` order by a.sort desc limit 8`, c.Uid)
			var evaluate orm.Params
			var enum int
			if evaluates := models.Query(`select a.id,a.score,a.img,a.addtime,a.content,c.pathname,b.monicker from mt_product_evaluation a left join mt_member b 
				on a.uid=b.id left join mt_resources c on b.avatar=c.id join (select * from mt_order_car where pid=` + id + `) d on a.cid=d.id where a.sid=0 and 
				a.status=1 and a.censoring=1`); evaluates != nil {
				evaluate = evaluates[0]
				if img := fmt.Sprint(evaluate["img"]); img != "" && img != "<nil>" {
					evaluate["imgs"] = models.Query(`select pathname from mt_resources where id in(` + img + `)`)
				}
				monicker := fmt.Sprint(evaluate["monicker"])
				monickers := strings.Split(monicker, "")
				evaluate["monicker"] = monickers[0] + `****` + monickers[len(monickers)-1]
				enum = len(evaluates)
			}
			gbuy := models.Query(`select id,price,endtime,num,min from mt_active_gbuy where end=0 and pid=` + id + ` and status=1 and starttime<='` + now + `' and endtime>'` + now + `' 
				order by addtime desc`)
			for _, v := range gbuy {
				endtime := fmt.Sprint(v["endtime"])
				nt := time.Now().Local()
				loc, _ := time.LoadLocation("Local")
				et, _ := time.ParseInLocation(Tparse, endtime, loc)
				res := et.Sub(nt)
				h := int(res.Hours())
				m := int(res.Minutes())
				s := int(res.Seconds())
				hi := h
				mi := m % 60
				si := s % 60
				var sysj []string
				if hi < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", hi))
				} else if hi >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", hi))
				}
				if mi < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", mi))
				} else if mi >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", mi))
				}
				if si < 10 {
					sysj = append(sysj, fmt.Sprintf("0%v", si))
				} else if si >= 10 {
					sysj = append(sysj, fmt.Sprintf("%v", si))
				}
				v["sysj"] = strings.Join(sysj, ":")
				jnum := models.Query(`select sum(b.num) as jnum from mt_order a join mt_order_car b on a.carid=b.id where a.type=1 and 
					a.status>=2 and a.agid=` + v["id"].(string))[0]["jnum"]
				if jnum == nil {
					v["jnum"] = "0"
				} else {
					v["jnum"] = jnum
				}
			}
			coupon := models.Query(`select id,name,full,offer,effective,date_format(starttime,'%Y-%m-%d') as starttime,date_format(endtime,'%Y-%m-%d') 
				as endtime from mt_coupon where status=1 and starttime<='` + now + `' and endtime>'` + now + `' and gid=` + gidcou)
			for _, v := range coupon {
				v["isget"] = 0
				if c.Uid != "" {
					if is := models.Query(`select id from mt_member_coupon where uid=` + c.Uid + ` and yid=` + v["id"].(string) + ` and status=1`); is != nil {
						v["isget"] = 1
					}
				}
			}
			service := models.Query(`select id,monicker from mt_member where status=1 and service=1`)
			if Isajax {
				var js = make(map[string]interface{})
				if gbuy != nil {
					js["gbuy"] = gbuy[0]
				}
				js["service"] = service
				js["iscollect"] = iscollect
				product[0]["content"] = sword.UeditorChange(models.Urlc, fmt.Sprint(product[0]["content"]))
				js["info"] = product[0]
				js["shop"] = shop
				js["shopcarnum"] = shopcarnum
				js["recommend"] = recommend
				js["evaluate"] = evaluate
				js["enum"] = enum
				js["coupon"] = coupon
				c.Data["json"] = js
				c.ServeJSON()
			} else {
				if gbuy != nil {
					c.Data["gbuy"] = gbuy[0]
				}
				c.Data["s_title"] = product[0]["title"]
				c.Data["service"] = service
				c.Data["s_desc"] = product[0]["description"]
				c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
				c.Data["s_img"] = product[0]["pathname"]
				c.Data["iscollect"] = iscollect
				c.Data["info"] = product[0]
				c.Data["shop"] = shop
				c.Data["shopcarnum"] = shopcarnum
				c.Data["recommend"] = recommend
				c.Data["evaluate"] = evaluate
				c.Data["enum"] = enum
				c.Data["coupon"] = coupon
				c.TplName = "wechat/column/product_content.html"
			}
		} else {
			if product := models.Query(`select cid from mt_product where id=` + id); product != nil {
				cid := product[0]["cid"].(string)
				recommend := ProductList(`select a.price,a.id,b.pathname,a.title,a.isvip from mt_product a left join mt_resources b on 
				a.img=b.id where a.cid=`+cid+` and a.status=1 and a.censoring=1 and a.recommend=1 and a.id<>`+id+` order by a.sort desc limit 8`, c.Uid)
				if c.IsAjax() {
					var js = make(map[string]interface{})
					js["npr"] = recommend
					c.Data["json"] = js
					c.ServeJSON()
				} else {
					c.Data["recommend"] = recommend
					c.TplName = "wechat/column/noproduct.html"
				}
			} else {
				c.StopRun()
			}
		}
	} else {
		c.StopRun()
	}
}
func (c *ColumnProductContent) Post() {
	defer c.ServeJSON()
	yid := c.GetString("yid")
	if yid == "" {
		c.Data["json"] = 0
		return
	}
	if c.Uid == "" {
		c.Data["json"] = 2
		return
	}
	if is := models.Query(`select id from mt_member_coupon where status=1 and uid=` + c.Uid + ` and yid=` + yid); is != nil {
		c.Data["json"] = 3
		return
	}
	if err := models.Exec(`insert into mt_member_coupon (uid,yid,addtime,status) values (` + c.Uid + `,` + yid + `,'` + sword.Gettimes("") + `',1)`); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}

}

type ColumnProductCollect struct {
	BaseController
}

func (c *ColumnProductCollect) Post() {
	defer c.ServeJSON()
	if c.Uid == "" {
		c.Data["json"] = 2
	} else {
		id := c.GetString("id")
		if id != "" {
			if is := models.Query(`select id from mt_member_collection where uid=` + c.Uid + ` and pid=` + id); is != nil {
				if err := models.Exec(`delete from mt_member_collection where id=` + is[0]["id"].(string)); err != nil {
					beego.Debug(err)
					c.Data["json"] = 0
				} else {
					c.Data["json"] = 1
				}
			} else {
				if err := models.Exec(`insert into mt_member_collection (uid,pid,addtime) values (` + c.Uid + `,` + id + `,'` + sword.Gettimes("") + `')`); err != nil {
					beego.Debug(err)
					c.Data["json"] = 0
				} else {
					c.Data["json"] = 1
				}
			}
		}
	}
}

type ColumnProductLost struct {
	BaseController
}

func (c *ColumnProductLost) Post() {
	defer c.ServeJSON()
	if c.Uid == "" {
		c.Data["json"] = 2
	} else {
		if is := models.Query(`select id from mt_product_lost where pid=` + c.GetString("pid") + ` and uid=` + c.Uid); is != nil {
			c.Data["json"] = 3
		} else {
			if err := models.Exec(fmt.Sprintf(`insert into mt_product_lost (uid,pid,num,addtime) values ('%v','%v','%v','%v')`, c.Uid, c.GetString("pid"),
				c.GetString("num"), sword.Gettimes(""))); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		}
	}
}

type ColumnList struct {
	BaseController
}

func (c *ColumnList) Get() {
	proStructId := c.GetString("proStructId")
	proStructPids := ""
	if proStructId != "" {
		if proStruct := models.Query(`select pid from mt_goods_struct where id=?`, proStructId); proStruct[0]["pid"] != nil {
			proStructPids = proStruct[0]["pid"].(string)
		}
	}
	shopWhere := ""
	if proStructId == "" {
		if c.ShopId != "" {
			shopWhere = "a.gid = " + c.ShopId + " and"
		} else {
			shopWhere = "a.gid not in(" + c.ShopIdAll + ") and"
		}
	}
	cid := c.GetString("id")
	if cid == "" {
		c.StopRun()
	}
	column := models.Query(`select a.id,a.level,a.pid,a.name,b.pathname from mt_column a left join mt_resources b on a.img=b.id where a.id=` + cid)[0]
	level := fmt.Sprint(column["level"])
	var cids []string
	cids = append(cids, cid)
	var pcid string
	if level == "2" {
		columns := models.Query(`select id from mt_column where pid=` + cid + ` and gid=0 and status=1`)
		for _, v := range columns {
			cids = append(cids, v["id"].(string))
		}
		pcid = cid
	} else {
		pcid = fmt.Sprint(column["pid"])
	}
	urls := `/mobile/column/list?`
	attribute_column := models.Query(`select id,name from mt_product_attribute_column where status=1 and cid=` + pcid + ` order by sort desc`)
	var w []string
	for _, v := range attribute_column {
		aid := v["id"].(string)
		v["attribute"] = models.Query(`select id,name from mt_product_attribute where cid=` + aid)
		paid := c.GetString(aid)
		if paid != "" {
			w = append(w, `a.attr like '%`+paid+`%'`)
			urls += aid + `=` + paid + `&`
			v["value"] = paid
		}
	}
	brand := models.Query(`select id,name from mt_brand where cid like '%` + cid + `,%' order by sort desc`)
	if proStructId != "" {
		w = append(w, `a.id in(`+proStructPids+`)`)
		var cidArr []string
		cidArr = append(cidArr, cid)
		column1 := models.Query(`select id,pid from mt_column where pid=? and status=1`, cid)
		if column1 != nil {
			for _, v := range column1 {
				id := v["id"].(string)
				cidArr = append(cidArr, id)
				column2 := models.Query(`select id,pid from mt_column where pid=? and status=1`, id)
				if column2 != nil {
					for _, v := range column2 {
						cidArr = append(cidArr, v["id"].(string))
					}
				}
			}
		}
		cids := strings.Join(cidArr, ",")
		w = append(w, `a.cid in(`+cids+`)`)
	}
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	cidss := strings.Join(cids, ",")
	if proStructId == "" {
		w = append(w, `a.cid in(`+cidss+`)`)
	}
	status := c.GetString("status")
	var ob string
	switch status {
	case "":
		ob = ` order by a.recommend desc,a.sort desc,a.addtime desc`
	case "0":
		ob = ` order by a.price desc`
	case "1": //价格
		ob = ` order by a.price`
	case "2": //价格
		ob = ` order by a.sellnum desc`
	case "3": //类别
		ob = ` order by (select pid from mt_column where e.pid=id), e.pid, a.cid, a.addtime desc`
	}
	bid := c.GetString("bid")
	if bid != "" {
		w = append(w, `a.bid=`+bid)
	}
	min := c.GetString("min")
	if min != "" {
		w = append(w, `a.price>=`+min)
	}
	max := c.GetString("max")
	if max != "" {
		w = append(w, `a.price<=`+max)
	}
	ws := strings.Join(w, ` and `)
	page, _, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.title,a.cid,a.keywords,a.price,a.gid,a.id,a.isvip,a.minbuy,a.sellnum,a.issellnum,b.pathname,c.name as gname,d.name as shen from 
	mt_product a 
	left join mt_resources b on a.img=b.id 
	left join (select * from mt_shop where style=1) c on a.gid=c.id 
	left join mt_area d on c.province=d.id 
	left join mt_column e on a.cid=e.id
	where ` + shopWhere + ` ` + ws + ob + lt
	info := ProductList(sql, c.Uid)
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["info"] = info
		js["brand"] = brand
		js["attribute_column"] = attribute_column
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["info"] = info
		c.Data["brand"] = brand
		c.Data["title"] = column["name"]
		c.Data["s_title"] = column["name"]
		c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
		c.Data["s_img"] = column["pathname"]
		c.Data["attribute_column"] = attribute_column
		c.Data["status"] = status
		c.Data["min"] = min
		c.Data["max"] = max
		c.Data["bid"] = bid
		c.Data["urls"] = urls + `min=` + min + `&max=` + max + `&bid=` + bid + `&id=` + cid
		c.Data["urlss"] = `/mobile/column/list?id=` + cid + `&status=` + status + `&proStructId=` + proStructId + `&`
		// c.Data["urlajax"] = `/mobile/column/search_result?keywords=` + keywords + `&status=` + status
		c.TplName = "wechat/column/list.html"
	}
}

type ColumnProductEvaluate struct {
	BaseController
}

func (c *ColumnProductEvaluate) Get() {
	id := c.GetString("id")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	w = append(w, `a.sid=0`)
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc `
	page, _, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.id,a.score,a.img,a.addtime,a.content,c.pathname,b.monicker from mt_product_evaluation a left join mt_member b 
				on a.uid=b.id left join mt_resources c on b.avatar=c.id join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where ` + ws + ob + lt
	info := models.Query(sql)
	for _, v := range info {
		monicker := fmt.Sprint(v["monicker"])
		monickers := strings.Split(monicker, "")
		v["monicker"] = monickers[0] + `****` + monickers[len(monickers)-1]
		if img := fmt.Sprint(v["img"]); img != "" && img != "<nil>" {
			v["imgs"] = models.Query(`select pathname from mt_resources where id in(` + img + `)`)
		}
	}
	all := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where ` + ws)[0]["num"]
	good := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score>3 and ` + ws)[0]["num"]
	middle := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score=3 and ` + ws)[0]["num"]
	nogood := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.score<3 and ` + ws)[0]["num"]
	pic := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + id + `) d on 
				a.cid=d.id where a.img<>'' and ` + ws)[0]["num"]
	product := models.Query(`select a.title,a.description,b.pathname from mt_product a left join mt_resources b on a.img=b.id`)[0]
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["info"] = info
		js["all"] = all
		js["good"] = good
		js["middle"] = middle
		js["nogood"] = nogood
		js["pic"] = pic
		js["product"] = product
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["info"] = info
		c.Data["all"] = all
		c.Data["good"] = good
		c.Data["middle"] = middle
		c.Data["nogood"] = nogood
		c.Data["pic"] = pic
		c.Data["s_title"] = product["title"].(string) + `的评价`
		c.Data["s_desc"] = product["description"]
		c.Data["s_url"] = Url + c.Ctx.Request.RequestURI
		c.TplName = "wechat/column/product_evaluate.html"
	}
}

type ContactService struct {
	BaseController
}

func (c *ContactService) Get() {
	id := c.GetString("id")
	gid := models.Query(`select gid from mt_member where id=` + id)[0]["gid"].(string)
	if gid == "0" {
		if c.Uid != "" {
			sid := fmt.Sprint(models.Query(`select sid from mt_member where id=` + c.Uid)[0]["sid"])
			var sids []string
			if sid == "" || sid == "<nil>" || sid == "0" {
				service := models.Query(`select id from mt_member where service=1`)
				for _, v := range service {
					sids = append(sids, v["id"].(string))
				}
			}
			for _, v := range sids {
				if is := models.Query(`select id from mt_sms where (uid=` + c.Uid + ` and fid=` + v + `) or (fid=` + c.Uid + ` and uid=` + v + `)`); is != nil {
					sid = v
					models.Exec(`update mt_member set sid=` + sid + ` where id=` + c.Uid)
					break
				}
			}
			if sid == "" || sid == "<nil>" || sid == "0" {
				r := rand.New(rand.NewSource(time.Now().UnixNano()))
				sid = sids[r.Intn(len(sids))]
			}
			if sid == "" || sid == "<nil>" || sid == "0" {
				sid = fmt.Sprint(models.Systems()["uid"])
			}
			if c.IsAjax() {
				c.Data["json"] = sid
				c.ServeJSON()
			} else {
				c.Ctx.Redirect(302, "/mobile/my/message_content?id="+id)
			}
		} else {
			c.Ctx.Redirect(302, "/mobile/login")
		}
	} else {
		var uids []string
		service := models.Query(`select id from mt_member where gid=` + gid + ` and service=1`)
		for _, v := range service {
			uids = append(uids, v["id"].(string))
		}
		var uid string
		for _, v := range uids {
			if is := models.Query(`select id from mt_sms where (uid=` + c.Uid + ` and fid=` + v + `) or (fid=` + c.Uid + ` and uid=` + v + `)`); is != nil {
				uid = v
				break
			}
		}
		if uid == "" {
			if len(uids) > 0 {
				r := rand.New(rand.NewSource(time.Now().UnixNano()))
				uid = uids[r.Intn(len(uids))]
			}
		}
		if uid == "" {
			uid = models.Query(`select uid from mt_shop where id=` + gid)[0]["uid"].(string)
		}
		if c.IsAjax() {
			c.Data["json"] = uid
			c.ServeJSON()
		} else {
			c.Ctx.Redirect(302, "/mobile/my/message_content?id="+id)
		}
	}
}

type ProductStruct struct {
	BaseController
}

func (c *ProductStruct) Get() {
	id := c.GetString("id")
	search := c.GetString("search")
	classifyId := ""
	var info orm.Params
	if id != "" {
		classifyId = id
		info = models.Query(`select a.id,a.pid,a.type,b.pathname from mt_goods_struct a 
		left join mt_resources b on a.img=b.id
		where a.status=1 and a.id=?`, classifyId)[0]
	} else {
		info = models.Query(`select a.id,a.pid,a.type,b.pathname from mt_goods_struct a 
		left join mt_resources b on a.img=b.id
		where a.status=1`)[0]
		classifyId = fmt.Sprint(info["id"])
	}
	classify := models.Query(`select id,name,themeColor from mt_goods_struct where status=1`)
	currentColor := ""
	for _, v := range classify {
		id := fmt.Sprint(v["id"])
		if id == classifyId {
			currentColor = fmt.Sprint(v["themeColor"])
			break
		}
	}
	if search != "" {
		info["type"] = "0"
	}
	var res []orm.Params
	if info["pid"] != nil {
		pid := info["pid"].(string)
		if info["type"].(string) == "0" {
			var cidArr []string
			column := models.Query(`select id from mt_column where type='p' and status=1 and pid=0`)
			for _, c1 := range column {
				cidArr = append(cidArr, c1["id"].(string))
				column := models.Query(`select id,pid from mt_column where pid=? and status=1`, c1["id"].(string))
				for _, c2 := range column {
					cidArr = append(cidArr, c2["id"].(string))
					column := models.Query(`select id,pid from mt_column where pid=? and status=1`, c2["id"].(string))
					for _, c3 := range column {
						cidArr = append(cidArr, c3["id"].(string))
					}
				}
			}
			cidStr := strings.Join(cidArr, ",")
			page, _, num := models.Pagechange(c.GetString("page"), "")
			productsSql := `select a.id,a.title,a.isvip,a.click,a.minbuy,a.price,b.pathname,a.barcode from mt_product a 
				left join mt_resources b on a.img=b.id 
				where a.censoring=1 and a.status=1 and a.id in(` + pid + `) and a.cid in (` + cidStr + `) and title like '%` + search + `%'
				order by a.recommend desc,a.sort desc 
				limit ` + page + `,` + num
			res = ProductList(productsSql, c.Uid)
			var barcodeArr []string
			if c.ShopId != "0" && c.ShopId != "" {
				for _, v := range res {
					barcodeArr = append(barcodeArr, v["barcode"].(string))
				}
				barcodeStr := strings.Join(barcodeArr, ",")
				productsSql2 := `select a.id,a.title,a.isvip,a.click,a.minbuy,a.price,b.pathname,a.barcode from mt_product a
					left join mt_resources b on a.img=b.id
					where a.censoring=1 and a.status=1 and gid=` + c.ShopId + ` and a.barcode in(` + barcodeStr + `) and a.cid in (` + cidStr + `) and title like '%` + search + `%'
					order by a.recommend desc,a.sort desc
					limit ` + page + `,` + num
				res = ProductList(productsSql2, c.Uid)
			}
		} else {
			var result []orm.Params
			column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
			for i1, c1 := range column {
				var cidArr []interface{}
				id := c1["id"].(string)
				column1 := models.Query(`select a.name,a.id,b.pathname from mt_column a 
					left join mt_resources b on a.img=b.id where a.pid=? and a.status=1`, id)
				for _, c2 := range column1 {
					id := c2["id"].(string)
					// obj := make(map[string]interface{})
					// obj["id"] = id
					// obj["name"] = c2["name"].(string)
					// obj["pathname"] = fmt.Sprint(c2["pathname"])
					// cidArr = append(cidArr, obj)
					column2 := models.Query(`select a.name,a.id,b.pathname from mt_column a 
					left join mt_resources b on a.img=b.id where a.pid=? and a.status=1`, id)
					for _, c3 := range column2 {
						id := c3["id"].(string)
						pro := models.Query(`select id from mt_product where cid=? and id in(`+pid+`)`, id)
						if pro == nil {
							continue
						}
						obj := make(map[string]interface{})
						obj["id"] = id
						obj["name"] = c3["name"].(string)
						obj["pathname"] = fmt.Sprint(c3["pathname"])
						cidArr = append(cidArr, obj)
					}
				}
				c1["ctn"] = cidArr
				if len(cidArr) != 0 {
					result = append(result, column[i1])
				}
			}
			res = result
		}
	}
	beego.Debug(111)
	if c.IsAjax() {
		json := make(map[string]interface{})
		json["classify"] = classify
		json["currentColor"] = currentColor
		json["res"] = res
		json["info"] = info
		c.Data["json"] = json
		c.ServeJSON()
	}
	c.Data["classify"] = classify
	c.Data["classifyId"] = classifyId
	c.Data["currentColor"] = currentColor
	c.Data["info"] = info
	c.Data["res"] = res
	c.TplName = "wechat/index/product-struct.html"
}

type IsProductStructShowcase struct {
	BaseController
}

func (c *IsProductStructShowcase) Get() {
	cid := c.GetString("cid")
	sid := c.GetString("sid")
	info := models.Query(`select a.imgs from mt_goods_struct_imgs a 
		where a.cid=? and a.sid=?`, cid, sid)
	js := make(map[string]interface{})
	js["status"] = 0
	if info != nil && info[0]["imgs"] != nil && info[0]["imgs"] != "" {
		js["status"] = 1
	}
	c.Data["json"] = js
	c.ServeJSON()
}

type IsProductStructWindowcase struct {
	BaseController
}

func (c *IsProductStructWindowcase) Get() {
	sid := c.GetString("sid")
	info := models.Query(`select a.imgs from mt_product_struct_imgs a 
		where a.sid=?`, sid)
	js := make(map[string]interface{})
	js["status"] = 0
	if info != nil && info[0]["imgs"] != nil && info[0]["imgs"] != "" {
		js["status"] = 1
	}
	c.Data["json"] = js
	c.ServeJSON()
}

type ProductStructWindowcase struct {
	BaseController
}

func (c *ProductStructWindowcase) Get() {
	sid := c.GetString("sid")
	info := models.Query(`select a.imgs,a.click,date_format(a.time,'%Y-%m-%d') as time,a.introduce,b.name from mt_product_struct_imgs a 
		left join mt_goods_struct b on a.sid=b.id 
		where a.sid=?`, sid)
	var pathname []orm.Params
	if info != nil {
		imgStr := info[0]["imgs"].(string)
		pathname = models.Query(`select pathname from mt_resources where id in(` + imgStr + `)`)
	}
	if err := models.Exec(`update mt_product_struct_imgs set click=click+1 where sid=?`, sid); err != nil {
		beego.Debug(err)
	}
	if c.IsAjax() {
		js := make(map[string]interface{})
		js["pathname"] = pathname
		js["info"] = info[0]
		c.Data["json"] = js
		c.ServeJSON()
	}
	c.Data["pathname"] = pathname
	c.Data["info"] = info[0]
	c.TplName = "wechat/index/product-struct-showcase.html"
}

type ProductStructShowcase struct {
	BaseController
}

func (c *ProductStructShowcase) Get() {
	cid := c.GetString("cid")
	sid := c.GetString("sid")
	info := models.Query(`select a.imgs,a.click,date_format(a.time,'%Y-%m-%d') as time,a.introduce,b.name from mt_goods_struct_imgs a 
		left join mt_column b on a.cid=b.id 
		where a.cid=? and a.sid=?`, cid, sid)
	var pathname []orm.Params
	if info != nil {
		imgStr := info[0]["imgs"].(string)
		pathname = models.Query(`select pathname from mt_resources where id in(` + imgStr + `)`)
	}
	if err := models.Exec(`update mt_goods_struct_imgs set click=click+1 where cid=? and sid=?`, cid, sid); err != nil {
		beego.Debug(err)
	}
	if c.IsAjax() {
		js := make(map[string]interface{})
		js["pathname"] = pathname
		js["info"] = info[0]
		c.Data["json"] = js
		c.ServeJSON()
	}
	c.Data["pathname"] = pathname
	c.Data["info"] = info[0]
	c.TplName = "wechat/index/product-struct-showcase.html"
}
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
